package com.shuaigef.springbootinit.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.shuaigef.springbootinit.common.BaseResponse;
import com.shuaigef.springbootinit.common.ErrorCode;
import com.shuaigef.springbootinit.common.ResultUtils;
import com.shuaigef.springbootinit.exception.BusinessException;
import com.shuaigef.springbootinit.model.dto.classroom.ClassroomAddRequest;
import com.shuaigef.springbootinit.model.dto.classroom.ClassroomQueryRequest;
import com.shuaigef.springbootinit.model.dto.course.CourseAiRequest;
import com.shuaigef.springbootinit.model.dto.exercise.ExerciseAddRequest;
import com.shuaigef.springbootinit.model.entity.*;
import com.shuaigef.springbootinit.model.enums.RoleEnum;
import com.shuaigef.springbootinit.service.*;
import com.shuaigef.springbootinit.utils.MoonshotAiUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static com.shuaigef.springbootinit.model.enums.ExerciseDifficulty.getDifficultyByLevel;

/**
 * 班级接口
 */
@RestController
@RequestMapping("/classroom")
@Slf4j
public class ClassroomController {
    @Resource
    private  ClassroomService classroomService;
    @Resource
    private ExerciseService exerciseService;
    @Resource
    private PaperService paperService;
    @Resource
    private CourseService courseService;
    @Resource
    private PaperCourseService paperCourseService;
    /**
     * 新建班级
     */
    @PostMapping("/create")
    public BaseResponse<Void> createClassroom(@RequestBody ClassroomAddRequest classroomAddRequest) {
        return classroomService.createClassroom(classroomAddRequest);
    }

    /**
     * 获取教师管理的班级列表
     */
    @GetMapping("/list/teacher")
    public BaseResponse<List<Classroom>> listTeacherClassrooms() {
        List<Classroom> classrooms = classroomService.getLoginTeacherClassrooms();
        return ResultUtils.success(classrooms);
    }

    /**
     * 获取学生所在的班级列表
     */
    @GetMapping("/list/student")
    public BaseResponse<List<Classroom>> listStudentClassrooms() {
        List<Classroom> classrooms = classroomService.getLoginStudentClassrooms();
        return ResultUtils.success(classrooms);
    }

    /**
     * 根据id获取班级信息
     */
    @GetMapping("/get")
    public BaseResponse<Classroom> getClassroomById(Integer id) {
        Classroom classroom = classroomService.getClassroomById(id);
        return ResultUtils.success(classroom);
    }

    /**
     * 根据条件查询班级
     */
    @PostMapping("/query")
    public BaseResponse<List<Classroom>> queryClassrooms(@RequestBody ClassroomQueryRequest classroomQueryRequest) {
        List<Classroom> classrooms = classroomService.queryClassrooms(classroomQueryRequest);
        return ResultUtils.success(classrooms);
    }
    /**
     * 生成题目
     *
     */
    @PostMapping("/exercise")
    @Transactional
    public BaseResponse<Boolean> exercise(@RequestBody ExerciseAddRequest exerciseAddRequest)
            throws JsonProcessingException {

        if (exerciseAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String question = null;
        String answerKey = null;
        // Long count = 0L;
        String response = exerciseService.getExercise(exerciseAddRequest);
        System.out.println(response);
        String symbol = null;
        if (response != null && !response.isEmpty()) {
            // ObjectMapper mapper = new ObjectMapper();
            // JsonNode rootNode = mapper.readTree(response);
            // question = rootNode.get("question").asText();
            // answerKey = rootNode.get("answer").asText();
            JSONObject jsonResponse = new JSONObject(response);
            question = jsonResponse.getStr("question");
            answerKey = jsonResponse.getStr("answer");// 获取答案的键，如 "A"
            symbol = jsonResponse.getStr("symbol");
            System.err.println(answerKey);
            System.err.println(question);
        }
        if (question == null || answerKey == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请稍后再试");
        }
        // LambdaQueryWrapper<Exercise> queryWrapper = new LambdaQueryWrapper<>();
        // queryWrapper.eq(Exercise::getExerciseContent, question);
        // queryWrapper.eq(Exercise::getExerciseAnswer, answerKey);
        // count = exerciseService.getBaseMapper().selectCount(queryWrapper);
        // while (count > 0) {
        // response =exerciseService.getRepeatExercise(exerciseAddRequest, question,
        // answerKey);
        // System.err.println(response);
        // if (response != null && !response.isEmpty()) {
        // JSONObject jsonResponse = new JSONObject(response);
        // question = jsonResponse.getStr("question");
        // System.out.println("题目内容: " + question);
        // answerKey = jsonResponse.getStr("answer");// 获取答案的键，如 "A"
        // System.err.println(answerKey);
        // }
        // if (question == null || answerKey == null) {
        // throw new BusinessException(ErrorCode.OPERATION_ERROR, "请稍后再试");
        // }
        // count = exerciseService.getBaseMapper().selectCount(queryWrapper);
        // }
        // 将添加题目
        Exercise exercise = Exercise.builder()
                .exerciseAnswer(answerKey)
                .exerciseContent(question)
                .exerciseType(exerciseAddRequest.getExerciseType())
                .exerciseDifficulty(getDifficultyByLevel(Integer.parseInt(exerciseAddRequest.getExerciseDifficulty())).getLabel())
                .exerciseSymbol(symbol)
                .build();
        boolean result = exerciseService.save(exercise);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        Course course = courseService.getBaseMapper()
                .selectOne(new QueryWrapper<Course>().eq("course_name", exerciseAddRequest.getCourseName()));
        // 将题目添加到题库
        Paper paper = paperService.getBaseMapper()
                .selectOne(new QueryWrapper<Paper>().eq("paper_title", exerciseAddRequest.getPaperTitle()));
        int b = 0;
        // 如果题库不存在，则创建题库
        if (paper == null) {
            Paper paper1 = Paper.builder().paperTitle(exerciseAddRequest.getPaperTitle())
                    .paperContent(exercise.getExerciseId() + ",").build();
            b = paperService.getBaseMapper().insert(paper1);
            PaperCourse paperCourse = PaperCourse.builder().courseId(course.getCourseId()).paperId(paper1.getPaperId())
                    .build();
            paperCourseService.getBaseMapper().insert(paperCourse);
        }
        // 如果题库存在，则将题目添加到题库
        else {
            String paperContent = paper.getPaperContent();
            paperContent = paperContent + exercise.getExerciseId() + ",";
            paper.setPaperContent(paperContent);
            b = paperService.getBaseMapper().update(paper,
                    new QueryWrapper<Paper>().eq("paper_title", exerciseAddRequest.getPaperTitle()));
        }

        if (b == 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加到题库失败");
        }

        return ResultUtils.success(true);
    }

    /**
     * ai教学设计自动化
     */
    @PostMapping("/teaching")
    public BaseResponse<CourseAiRequest> teaching(@RequestBody CourseAiRequest courseAiRequest) {
        String content = "我是一个大学courseName老师，请为我设计courseTitle这节课的教学设计和教学内容，这节课要courseDuration";
        content = content.replace("courseName", courseAiRequest.getCourseName());
        content = content.replace("courseTitle", courseAiRequest.getCourseTitle());
        content = content.replace("courseDuration", courseAiRequest.getCourseDuration());
        System.out.println(content);
        List<Message> messages = CollUtil.newArrayList(
                new Message(RoleEnum.system.name(),
                        "设计一个教学设计和教学内容，包括教学活动安排、时间分配、预期成果。这个教学设计需要包含至少3个互动环节，以提高学生的参与度和学习效果，使用以下json格式输出答案，注意,如果有表达式的一律用latex代码表示，将使用的latex代码及其中文含义以键值对的形式储存在symbol字典中。题目和答案无需额外的中文描述：{\n"
                                +
                                "  \"课程名称\": \"[课程名称]\",\n" +
                                "  \"适用对象\": \"[适用对象]\",\n" +
                                "  \"授课时长\": \"[总课时]分钟\",\n" +
                                "  \"课程目标\": [\n" +
                                "    \"[目标1]\",\n" +
                                "    \"[目标2]\",\n" +
                                "    \"[目标3]\",\n" +
                                "    \"（如有更多目标可继续添加）\"\n" +
                                "  ],\n" +
                                "  \"课程内容\": [\n" +
                                "    \"[内容1]\",\n" +
                                "    \"[内容2]\",\n" +
                                "    \"[内容3]\",\n" +
                                "    \"（后续内容依次列出）\"\n" +
                                "  ],\n" +
                                "  \"教学活动\": {\n" +
                                "    \"[活动1名称]\": {\n" +
                                "      \"活动内容\": [\n" +
                                "        \"[活动1内容1]\",\n" +
                                "        \"[活动1内容2]\",\n" +
                                "        \"（如有更多内容可继续添加）\"\n" +
                                "      ],\n" +
                                "      \"时间安排\": \"[活动1时间]分钟\"\n" +
                                "    },\n" +
                                "    \"[活动2名称]\": {\n" +
                                "      \"活动内容\": [\n" +
                                "        \"[活动2内容1]\",\n" +
                                "        \"[活动2内容2]\",\n" +
                                "        \"（后续内容依次列出）\"\n" +
                                "      ],\n" +
                                "      \"时间安排\": \"[活动2时间]分钟\"\n" +
                                "    },\n" +
                                "    \"[活动3名称]\": {\n" +
                                "      \"活动内容\": [\n" +
                                "        \"[活动3内容1]\",\n" +
                                "        \"[活动3内容2]\",\n" +
                                "        \"（后续内容依次列出）\"\n" +
                                "      ],\n" +
                                "      \"时间安排\": \"[活动3时间]分钟\"\n" +
                                "    }\n" +
                                "    // （如有更多教学活动可继续添加）\n" +
                                "  },\n" +
                                "  \"预期成果\": [\n" +
                                "    \"[成果1]\",\n" +
                                "    \"[成果2]\",\n" +
                                "    \"[成果3]\",\n" +
                                "    \"（如有更多预期成果可继续添加）\"\n" +
                                "  ],\n" +
                                "  \"互动环节\": [\n" +
                                "    {\n" +
                                "      \"互动环节名称\": \"[互动环节1名称]\",\n" +
                                "      \"形式\": \"[形式1]\",\n" +
                                "      \"内容\": \"[内容1]\",\n" +
                                "      \"时间分配\": \"[时间1]分钟\"\n" +
                                "    },\n" +
                                "    {\n" +
                                "      \"互动环节名称\": \"[互动环节2名称]\",\n" +
                                "      \"形式\": \"[形式2]\",\n" +
                                "      \"内容\": \"[内容2]\",\n" +
                                "      \"时间分配\": \"[时间2]分钟\"\n" +
                                "    },\n" +
                                "    {\n" +
                                "      \"互动环节名称\": \"[互动环节3名称]\",\n" +
                                "      \"形式\": \"[形式3]\",\n" +
                                "      \"内容\": \"[内容3]\",\n" +
                                "      \"时间分配\": \"[时间3]分钟\"\n" +
                                "    }\n" +
                                "    // （如有更多互动环节可继续添加）\n" +
                                "  ],\n" +
                                "  \"课后作业\": [\n" +
                                "    \"[作业1]\",\n" +
                                "    \"[作业2]\",\n" +
                                "    \"（如有更多作业可继续添加）\"\n" +
                                "  ]\n" +
                                "}"),
                new Message(RoleEnum.user.name(), content));
        String response = MoonshotAiUtils.chat("moonshot-v1-8k", messages);
        if (StringUtils.isEmpty(response)) {
            throw new RuntimeException("请稍后再试");
        }
        CourseAiRequest courseAiRequest1 = new CourseAiRequest();
        JSONObject jsonObject = new JSONObject(response);
        System.out.println(response);
        courseAiRequest1.setName(jsonObject.getStr("课程名称"));
        courseAiRequest1.setCourseContent(jsonObject.getStr("课程内容"));
        courseAiRequest1.setCourseDuration(courseAiRequest.getCourseDuration());
        courseAiRequest1.setCourseGoal(jsonObject.getStr("课程目标"));
        courseAiRequest1.setCourseOutcome(jsonObject.getStr("预期成果"));
        courseAiRequest1.setCourseSchedule(jsonObject.getStr("教学活动"));
        courseAiRequest1.setCourseInteraction(jsonObject.getStr("互动环节"));
        courseAiRequest1.setCourseHomework(jsonObject.getStr("课后作业"));
        return ResultUtils.success(courseAiRequest1);
    }

} 